#!/bin/bash

echo "🚨 修复数据库迁移问题..."

cd /Users/zyu/leo/ignite-fun/backend

echo "1️⃣ 检查数据库连接..."
if ! npx prisma db push --accept-data-loss --preview-feature; then
    echo "❌ 数据库连接失败"
    exit 1
fi

echo "2️⃣ 重新生成Prisma客户端..."
npx prisma generate

echo "3️⃣ 验证迁移状态..."
npx prisma migrate status

echo "4️⃣ 如果需要，重置并重新应用迁移..."
read -p "是否需要重置数据库迁移？(y/N): " reset_db
if [[ $reset_db =~ ^[Yy]$ ]]; then
    echo "⚠️  重置迁移历史..."
    npx prisma migrate reset --force
    
    echo "📝 重新应用迁移..."
    npx prisma migrate deploy
fi

echo "5️⃣ 测试构建..."
if pnpm run build; then
    echo "✅ 构建成功！"
    
    echo "6️⃣ 重启服务..."
    cd ..
    pm2 restart all
    
    echo "7️⃣ 测试API..."
    sleep 3
    if curl -s http://localhost:7172/api/health > /dev/null; then
        echo "✅ 后端API正常"
        
        # 测试tokens端点
        if curl -s "http://localhost:7172/api/tokens?page=1&limit=5" > /dev/null; then
            echo "✅ Tokens API正常"
        else
            echo "❌ Tokens API异常"
            echo "📝 查看后端日志:"
            pm2 logs ignitefun-backend --lines 10
        fi
    else
        echo "❌ 后端API异常"
        echo "📝 查看后端日志:"
        pm2 logs ignitefun-backend --lines 10
    fi
else
    echo "❌ 构建失败，可能需要手动修复代码"
fi

echo ""
echo "🔧 如果问题持续，请检查："
echo "  1. 数据库是否正常运行"
echo "  2. .env文件中的DATABASE_URL是否正确"
echo "  3. 是否有语法错误"
echo "  4. 后端日志: pm2 logs ignitefun-backend"
